<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition End User License Agreement
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magento.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    Mage
 * @package     Mage_Adminhtml
 * @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
 * @license http://www.magento.com/license/enterprise-edition
 */

/**
 * Adminhtml sales orders grid
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Adminhtml_Block_Sales_Order_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

    public function __construct()
    {
        parent::__construct();
        $this->setId('sales_order_grid');
        $this->setUseAjax(true);
        $this->setDefaultSort('created_at');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
    }

    /**
     * Retrieve collection class
     *
     * @return string
     */
    protected function _getCollectionClass()
    {
        return 'sales/order_grid_collection';
    }

    protected function _prepareCollection()
    {  
        //获取当前站点Id 
        $websiteId = Mage::getSingleton('admin/session')->getUser()->getWebsiteId();
        
        $collection = Mage::getResourceModel($this->_getCollectionClass());


        if($websiteId){
            $website = new Mage_Core_Model_Website();
            $website->load($websiteId);
            $storeId = $website->getDefaultStore()->getId();
            $collection->addFieldToFilter('main_table.store_id',array('eq'=>$storeId));
        }
        $select = $collection->getSelect();

        $select->joinLeft(array('oe' => $collection->getTable('sales/order')), 'oe.entity_id=main_table.entity_id',
            array('oe.quote_id', 'oe.print', 'oe.shipping_id', 'oe.total_refunded', 'oe.subtotal'));

        $select->joinLeft(array('so' => $collection->getTable('order')), 'so.entity_id=main_table.entity_id', 
            array('total_item_count'=>'so.total_item_count','total_qty_ordered'=>"so.total_qty_ordered","app_id"=>"so.app_id"));

        $select->joinLeft(array('ts' => 'tms_shipping'), 'ts.id=oe.shipping_id',
            array('shipping_increment_id' => 'ts.increment_id'));


        $lastname  = Mage::getResourceModel('customer/customer')->getAttribute('lastname');
        $tablename = $lastname->getBackend()->getTable();
        $attributeId = $lastname->getAttributeId();
        $select->joinLeft(array('ce' => $tablename), "ce.entity_id=main_table.customer_id and ce.attribute_id='{$attributeId}'", array('customer_store_name'=>'ce.value'));

        /*Get Store Adderss*/
        $select->joinLeft(array('sfoa' => 'sales_flat_order_address'), "sfoa.entity_id = oe.shipping_address_id", array('customer_store_address_1'=>'sfoa.region', 'customer_store_address_2'=>'sfoa.city','customer_store_address_3'=>'sfoa.street'));
        
        $collection->addFilterToMap('customer_store_address_1','sfoa.region');
        $collection->addFilterToMap('customer_store_address_2','sfoa.city');
        $collection->addFilterToMap('customer_store_address_3','sfoa.street');
        
        //$select->joinLeft(array('wh' => $collection->getTable('zgb/warehouse')), 'wh.id=oe.warehouse_id',array('dealer_id'=>'wh.dealer_id'));

        //$collection->addFilterToMap('warehouse_id', 'oe.warehouse_id');
        $collection->addFilterToMap('quote_id', 'oe.quote_id');
        $collection->addFilterToMap('shipping_id', 'oe.shipping_id');

        $collection->addFilterToMap('shipping_increment_id', 'ts.increment_id');

        $collection->addFilterToMap('customer_store_name', 'ce.value');
        $collection->addFilterToMap('total_item_count', 'so.total_item_count');
        $collection->addFilterToMap('total_qty_ordered', 'so.total_qty_ordered');
        $collection->addFilterToMap('app_id', 'so.app_id');

        // $session = Mage::getSingleton('admin/session');
        // $userId = $session->getUser()->getId();
        // $roleId = $session->getUser()->getRoleId();

        // 不需要再进行角色判断
        // if($roleId == Mage::helper('zgb')->getRoleId('dealer'))
        // {
        //     $model = Mage::getModel('zgb/dealer')->loadByAdminId($userId);
        //     $collection->addFieldToFilter('warehouse_id', array('in'=>$model->getWarehouseIds()));
        // }
        // else if($roleId == Mage::helper('zgb')->getRoleId('warehouse'))
        // {
        //     $model = Mage::getModel('zgb/warehouse')->loadByAdminId($userId);
        //     $collection->addAttributeToFilter('warehouse_id', array('eq'=>$model->getId()));
        // }

        //$now =  strtotime(Mage::getModel('core/date')->date('Y-m-d H:i:s'))-3600*8;
        //echo Mage::getModel('core/date')->date('Y-m-d H:i:s', $now);
        //echo date("Y-m-d H:i:s",$now);

        $filterType = $this->getRequest()->getParam('filter_type');
        if($filterType)
        {
            if($filterType == "pending_timeout")
            {
                $rang = intval(Mage::getStoreConfig('sales/general/pending_timeout'));
                if($rang>0)
                {
                    $timestamp = time()-($rang)*3600;
                    $timeout = date("Y-m-d H:i:s",$timestamp);
                    $collection->addAttributeToFilter('main_table.status', array('eq'=>'pending'));
                    $collection->addAttributeToFilter('main_table.created_at', array('lt'=>$timeout));
                }
            }
            else if($filterType == "processing_timeout")
            {
                $rang = intval(Mage::getStoreConfig('sales/general/processing_timeout'));
                if($rang>0)
                {
                    $timestamp = time()-($rang)*3600;
                    $timeout = date("Y-m-d H:i:s",$timestamp);
                    $collection->addAttributeToFilter('main_table.status', array('nin'=>array('canceled','complete','closed','complete_order')));
                    $collection->addAttributeToFilter('main_table.created_at', array('lt'=>$timeout));
                }
            }
        }
        // else
        // {
        //     $collection->addAttributeToFilter('main_table.status', array('neq'=>'canceled'));
        // }


        $this->setCollection($collection);
        return parent::_prepareCollection();
    }
    protected function getStore(){
        $outs = array();
        //get store by current websiteId
        $websiteId = Mage::getSingleton('admin/session')->getUser()->getWebsiteId();
        if($websiteId != 0){
            $website = Mage::getModel('core/website')->load($websiteId);
            $storeIds = $website->getStoreIds();
            foreach ($storeIds as $storeId) {
                $store = Mage::getModel('core/store')->load($storeId);
                $outs[$store->getId()] =$store->getName();
            }
            return $outs;
        }
        $websites =  Mage::getModel('core/website')->getResourceCollection();
        foreach ($websites as $website) {
            if($website->getId()){
                foreach ($website->getGroups() as $group) {
                    if($group->getId()){
                        foreach ($group->getStores() as $store) {
                            $storeId = $store->getId();
                            $storeName = $store->getName();
                        }
                    }      
                }
            }      
        $outs[$storeId]=$storeName;
        }
        return $outs;  
        

             
    }
    protected function _prepareColumns()
    {

        $this->addColumn('real_order_id', array(
            'header'=> Mage::helper('sales')->__('Order #'),
            'width' => '80px',
            'type'  => 'text',
            'index' => 'increment_id',
            'filter_index'=>'main_table.increment_id',
        ));

        // $this->addColumn('quote_id', array(
        //     'header'=> Mage::helper('sales')->__('批次号 #'),
        //     'width' => '80px',
        //     'type'  => 'number',
        //     'index' => 'quote_id',
        // ));

        $this->addColumn('shipping_increment_id', array(
            'header' => Mage::helper('sales')->__('运单编号'),
            'width' => '30px',
            'type' => 'text',
            'index' => 'shipping_increment_id',
        ));

        if (!Mage::app()->isSingleStoreMode()) {
            $this->addColumn('store_id', array(
                'header'    => Mage::helper('sales')->__('下单地区'),
                'index'     => 'store_id',
                //'type'      =>  'store',
                'type'      => 'options',
                'options'   => $this->getStore(),
                'store_view'=> true,
                'display_deleted' => true,
                'width' => '60px',
                'filter_index'=>'main_table.store_id',
                'renderer' => 'Silk_Zgb_Block_Renderer_Removestore'
            ));
        }

        $this->addColumn('created_at', array(
            'header' => Mage::helper('sales')->__('Purchased On'),
            'index' => 'created_at',
            'filter_index'=>'main_table.created_at',
            'type' => 'datetime',
            'width' => '100px',
        ));

        // $this->addColumn('billing_name', array(
        //     'header' => Mage::helper('sales')->__('Bill to Name'),
        //     'index' => 'billing_name',
        // ));

        //=========================
        // $options = array();
        // $dealers = Mage::getModel('zgb/dealer')->toOptionArray();
        // foreach($dealers as $dealer)
        // {
        //     $options[$dealer['value']] = $dealer['label'];
        // }
        // $this->addColumn('dealer_id',
        //     array(
        //         'header'=> Mage::helper('catalog')->__('经销商'),
        //         'width' => '100px',
        //         'index' => 'dealer_id',
        //         'type'  => 'options',
        //         'options' => $options,
        // ));

        /*
        $warehouses = Mage::getModel('zgb/warehouse')->toOptionArray();
        $options = array();
        foreach($warehouses as $warehouse)
        {
            $options[$warehouse['value']] = $warehouse['label'];
        }
        $this->addColumn('warehouse_id', array(
            'header'    => Mage::helper('sales')->__('仓库'),
            'index'     => 'warehouse_id',
            'type'      => 'options',
            'options'   => $options,
            'width' => '100px',
            'filter_index'=>'oe.warehouse_id',
        ));
        */

        $this->addColumn('customer_store_name', array(
            'header' => Mage::helper('sales')->__('店铺名'),
            'index' => 'customer_store_name',
            'type'  => 'text',
            "width"   => "120px"
        ));

        // $this->addColumn('customer_store_address_1', array(
        //     'header' => Mage::helper('sales')->__('省'),
        //     'index' => 'customer_store_address_1',
        //     'type'  => 'text',
        //     "width"   => "50px"
        // ));
        // $this->addColumn('customer_store_address_2', array(
        //     'header' => Mage::helper('sales')->__('市区'),
        //     'index' => 'customer_store_address_2',
        //     'type'  => 'text',
        //     "width"   => "80px"
        // ));

        $this->addColumn('customer_store_address_3', array(
            'header' => Mage::helper('sales')->__('详细地址'),
            'index' => 'customer_store_address_3',
            'type'  => 'text',
            "width"   => "100px"
        ));

        $this->addColumn('shipping_name', array(
            'header' => Mage::helper('sales')->__('Ship to Name'),
            'index' => 'shipping_name',
            'renderer' => 'Silk_Zgb_Block_Renderer_Removename',
            "width"   => "80px"
        ));

        // $this->addColumn('base_grand_total', array(
        //     'header' => Mage::helper('sales')->__('G.T. (Base)'),
        //     'index' => 'base_grand_total',
        //     'type'  => 'currency',
        //     'currency' => 'base_currency_code',
        // ));
        $this->addColumn('total_item_count', array(
            'header' => Mage::helper('sales')->__('商品数'),
            'index' => 'total_item_count',
            'filter_index'=>'so.total_item_count',
            'width' => '50px',
            'type' => 'number',
        ));

        $this->addColumn('total_qty_ordered', array(
            'header' => Mage::helper('sales')->__('商品总数'),
            'index' => 'total_qty_ordered',
            'filter_index'=>'so.total_qty_ordered',
            'width' => '50px',
            'renderer' => 'Silk_Zgb_Block_Renderer_Int',
            'type' => 'number',
            'align' => 'right'
        ));

        $appId = array('0' => '其他', '101' => 'Android', "103" => "IOS");
        $this->addColumn('app_id', array(
            'header' => Mage::helper('sales')->__('设备'),
            'index' => 'app_id',
            "type" =>  "options",
            'options' => $appId,
            'width' => '50px',
        ));


        $this->addColumn('grand_total', array(
            'header' => Mage::helper('sales')->__('G.T. (Purchased)'),
            'index' => 'grand_total',
            'filter_index'=>'main_table.grand_total',
            'type'  => 'currency',
            'currency' => 'order_currency_code',

        ));

        $this->addColumn('subtotal_refunded', array(
            'header' => Mage::helper('sales')->__('实收款'),
            //'index' => 'entity_id',
            'filter_condition_callback' => array($this, 'filterSubtotalRefunded'),
            'type' => 'currency',
            'width' => '50px',
            'align' => 'right',
            'currency' => 'order_currency_code',
            'renderer' => 'Silk_Zgb_Block_Renderer_Total'
        ));

        $prints = array('0'=>'未打印','1'=>'已打印');
        
        $this->addColumn('print', array(
            'header' => Mage::helper('sales')->__('是否打印'),
            'index' => 'print',
            'filter_index'=>'oe.print',
            'type'  => 'options',
            'width' => '50px',
            'options' => $prints
        ));

        $isShipping = array('0' => '未分配', '1' => '已分配');
        $this->addColumn('is_shipping', array(
            'header' => Mage::helper('sales')->__('运单分配'),
            'filter_condition_callback' => array($this, 'filterIsShipping'),
            'type' => 'options',
            'width' => '45px',
            'options' => $isShipping,
            'renderer' => 'Silk_Zgb_Block_Renderer_Shipping'
        ));


        $status = array();
        $sysStatus = Mage::getSingleton('sales/order_config')->getStatuses();
        $allowStatus = array(
            'canceled',
            'closed',
            'complete',
            'processing',
            'pending',
            Silk_Tms_Helper_Status::MAGENTO_STATUS_COMPLETE_DELIVERING,
            Silk_Tms_Helper_Status::MAGENTO_STATUS_COMPLETE_SHIP,
            Silk_Tms_Helper_Status::MAGENTO_STATUS_COMPLETE_ORDER,
        );
        foreach($sysStatus as $key=>$val)
        {
            if(!in_array($key, $allowStatus)) continue;
            $status[$key] = Mage::helper('sales')->__($val);
        }

        $this->addColumn('status', array(
            'header' => Mage::helper('sales')->__('Status'),
            'index' => 'status',
            'filter_index'=>'main_table.status',
            'type'  => 'options',
            'width' => '70px',
            'options' => $status
        ));

        

        if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
            $this->addColumn('action',
                array(
                    'header'    => Mage::helper('sales')->__('Action'),
                    'width'     => '50px',
                    'type'      => 'action',
                    'getter'     => 'getId',
                    'actions'   => array(
                        array(
                            'caption' => Mage::helper('sales')->__('View'),
                            'url'     => array('base'=>'*/sales_order/view'),
                            'field'   => 'order_id',
                            'data-column' => 'action',
                        )
                    ),
                    'filter'    => false,
                    'sortable'  => false,
                    'index'     => 'stores',
                    'is_system' => true,
            ));
        }
        //$this->addRssList('rss/order/new', Mage::helper('sales')->__('New Order RSS'));

        //$this->addExportType('*/*/exportCsv', Mage::helper('sales')->__('CSV'));
        //$this->addExportType('*/*/exportExcel', Mage::helper('sales')->__('Excel XML'));

        return parent::_prepareColumns();
    }

    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('entity_id');
        $this->getMassactionBlock()->setFormFieldName('order_ids');
        $this->getMassactionBlock()->setUseSelectAll(false);

        if(Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/print'))
        {
            $this->getMassactionBlock()->addItem('print_shipping_label', array(
                'label'=> Mage::helper('sales')->__('打印出库单'),
                'url'  => $this->getUrl('*/sales_order/print'),
            ));
            $this->getMassactionBlock()->addItem('print_picking_label', array(
                'label'=> Mage::helper('sales')->__('打印拣货单'),
                'url'  => $this->getUrl('*/sales_order/printPicking'),
            ));
        }

        if(Mage::getSingleton('admin/session')->isAllowed('sales/shipping'))
        {
            if(Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/newshipping'))
            {
                $this->getMassactionBlock()->addItem('shipping_create', array(
                    'label'=> Mage::helper('sales')->__('创建运单'),
                    'url'  => $this->getUrl('*/sales_order/newshipping'),
                ));
            }
            if(Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/addshipping'))
            {
                $this->getMassactionBlock()->addItem('shipping_update', array(
                    'label'=> Mage::helper('sales')->__('加入运单'),
                    'url'  => $this->getUrl('*/sales_order/addshipping'),
                ));
            }
        }

        if(Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/ship'))
        {
            $this->getMassactionBlock()->addItem('shipping_order', array(
                 'label'=> Mage::helper('sales')->__('发货'),
                 'url'  => $this->getUrl('*/sales_order/shipping'),
            ));

            $this->getMassactionBlock()->addItem('shipping_complete', array(
                 'label'=> Mage::helper('sales')->__('配送完成'),
                 'url'  => $this->getUrl('*/sales_order/complete'),
            ));
        }

        if(Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/complete_order'))
        {
            $this->getMassactionBlock()->addItem('order_complete', array(
                'label' => Mage::helper('sales')->__('确认收款'),
                'url'   => $this->getUrl('*/sales_order/completeOrder'),
                'confirm' => Mage::helper('tms')->__('确认收款已收到货款?')
            ));
        }

        //if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/cancel')) {
        //   $this->getMassactionBlock()->addItem('cancel_order', array(
        //        'label'=> Mage::helper('sales')->__('Cancel'),
        //        'url'  => $this->getUrl('*/sales_order/massCancel'),
        //        'confirm'  => Mage::helper('customer')->__('你是否确认取消所选订单?')
        //    ));
        //}

        // if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/hold')) {
        //     $this->getMassactionBlock()->addItem('hold_order', array(
        //          'label'=> Mage::helper('sales')->__('Hold'),
        //          'url'  => $this->getUrl('*/sales_order/massHold'),
        //     ));
        // }

        // if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/unhold')) {
        //     $this->getMassactionBlock()->addItem('unhold_order', array(
        //          'label'=> Mage::helper('sales')->__('Unhold'),
        //          'url'  => $this->getUrl('*/sales_order/massUnhold'),
        //     ));
        // }

        // $this->getMassactionBlock()->addItem('pdfinvoices_order', array(
        //      'label'=> Mage::helper('sales')->__('Print Invoices'),
        //      'url'  => $this->getUrl('*/sales_order/pdfinvoices'),
        // ));

        // $this->getMassactionBlock()->addItem('pdfshipments_order', array(
        //      'label'=> Mage::helper('sales')->__('Print Packingslips'),
        //      'url'  => $this->getUrl('*/sales_order/pdfshipments'),
        // ));

        // $this->getMassactionBlock()->addItem('pdfcreditmemos_order', array(
        //      'label'=> Mage::helper('sales')->__('Print Credit Memos'),
        //      'url'  => $this->getUrl('*/sales_order/pdfcreditmemos'),
        // ));

        // $this->getMassactionBlock()->addItem('pdfdocs_order', array(
        //      'label'=> Mage::helper('sales')->__('Print All'),
        //      'url'  => $this->getUrl('*/sales_order/pdfdocs'),
        // ));

        // $this->getMassactionBlock()->addItem('print_shipping_label', array(
        //      'label'=> Mage::helper('sales')->__('Print Shipping Labels'),
        //      'url'  => $this->getUrl('*/sales_order_shipment/massPrintShippingLabel'),
        // ));

        return $this;
    }

    public function getRowUrl($row)
    {
        if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
            return $this->getUrl('*/sales_order/view', array('order_id' => $row->getId()));
        }
        return false;
    }

    public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', array('_current'=>true));
    }

    protected function filterSubtotalRefunded($collection, $column)
    {
        $value = $column->getFilter()->getValue();
        $from = $value['from'];
        $to = $value['to'];
        $select = $collection->getSelect();
        //add by wanglin start
        if($from){
        	/** @var Varien_Db_Select $select */
        	$select->where('(oe.subtotal-IFNULL(oe.total_refunded,0)) >= ' . $from);
        }
        if($to){
        	$select->where('(oe.subtotal-IFNULL(oe.total_refunded,0)) <= ' . $to);
        } 
        //add by wanglin end
       
    }

    protected function filterIsShipping($collection, $column)
    {
        $value = $column->getFilter()->getValue();

        /** @var Varien_Db_Select $select */
        $select = $collection->getSelect();

        if (!$value) {
            $select->where('ts.increment_id is null');
        } else {
            $select->where('ts.increment_id is not null');
        }
    }

}
